package com.foreknow.controller;

import com.foreknow.bean.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddMessageServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        //可以获取一些初始的配制信息
        //        String pageSize = config.getInitParameter("pageSize");
        //获取全局的初始化参数context_param
        String pageSize = config.getServletContext().getInitParameter("pageSize");
        System.out.println(pageSize);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器端向客户端响应的内容的类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        //客户端向服务器端请求的编码格式设置为utf-8
        req.setCharacterEncoding("utf-8");
        //通过response对象获取到PrintWriter打印流
        PrintWriter out = resp.getWriter();
        //获取到请求参数
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //调用Service中的方法
        GuestbookService service = new GuestbookServiceImpl();
        Guestbook gb = new Guestbook();
        gb.setName(name);
        gb.setPhone(phone);
        gb.setEmail(email);
        gb.setTitle(title);
        gb.setContent(content);
        Date date = new Date();//需要将Data转换为字符串
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        gb.setCreatedTime(simpleDateFormat.format(date));
        //保存数据
        boolean isRigth = service.save(gb);
        if(isRigth){
//            out.println("<a href='/WebCMSSystem/user/get'>query guestbook info</a>");
            //请求转发
//            req.getRequestDispatcher("/user/get").forward(req,resp);
            //重定向
             resp.sendRedirect(req.getContextPath()+"/user/manager?q=list");
        }else {
            out.println("error......");
        }
    }
}
